<?php Workerman\Protocols\Http::sessionStart(); $G_MODEL_NAME = basename(__FILE__,'.js.php'); $G_MODEL_URL = $_SESSION["MES_WEB_URL"].'/'. $G_MODEL_NAME; ?>
<?php $access_token = $_SESSION["ACCESS_TOKEN"];?>

for (var selector in chosen_config) {
	$(selector).chosen(chosen_config[selector]);
	$(".chosen-container ").css("width",$(selector).width());
}


//右上角菜单按键
$(".mod_btn_<?php echo $G_MODEL_NAME; ?>").on("click", function(e){
	mod_fun_action($(this).attr("data-tap"));
	return;
});


var oFormSetting = $('#<?php echo $G_MODEL_NAME; ?>_password_setting').validate({
	submitHandler:function(form){  
		//保存/修改
		var action = "password";
		if($('[name="mod_user_input_id_password_setting"]').val()==""){
			return false;
		}
        ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{
            action:action,
			id:$('[name="mod_user_input_id_password_setting"]').val(),
			password:$('[name="mod_user_input_password"]').val()
        },access_token:"<?php echo $access_token?>"},function(result){
            var result = JSON.parse(result);
			result = result["rtval"];
			if(result=="done"){
				//刷新数据
				oTable.ajax.reload();
				$('#dlg_<?php echo $G_MODEL_NAME; ?>_password_setting').modal('hide');
			}else{
				alert(result);
			}
        })
		return false;
	},
	 rules: {
		 mod_user_input_password: {
			required: true,
			minlength: 5
		 },
		 mod_user_input_repassword: {
			required: true,
			minlength: 5,
			equalTo: "#mod_user_input_password"
		 }
	 }
 });

var oForm = $('#<?php echo $G_MODEL_NAME; ?>_form').validate({
	submitHandler:function(form){  
		//保存/修改
		var action = "";
		if($('[name="mod_user_input_id"]').val()==""){
			//如果ID为空，新建一个记录
			action = "add";
		}else{
			//ID不为空，保存旧记录
			action = "edit";
		}
		var stat = 0;
		if($('[name="mod_user_input_stat"]').is(':checked')){
			stat = 1;
		}
		var is_department_head = 0;
		if($('[name="mod_user_input_is_department_head"]').is(':checked')){
			is_department_head = 1;
		}
		var is_department_headquarters_head = 0;
		if($('[name="mod_user_input_is_department_headquarters_head"]').is(':checked')){
			is_department_headquarters_head = 1;
		}
		var department_id = $('[name="mod_user_input_department"]').find("option:selected").val();
		var groups_id = $('[name="mod_user_input_groups"]').find("option:selected").val();
		ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{
            action:action,
			id:$('[name="mod_user_input_id"]').val(),
			name:$('[name="mod_user_input_name"]').val(),
			code:$('[name="mod_user_input_code"]').val(),
			user:$('[name="mod_user_input_user"]').val(),
			stat:stat,
			is_department_head:is_department_head,
			is_department_headquarters_head:is_department_headquarters_head,
			department:department_id,
			groups:groups_id,
			mobile:$('[name="mod_user_input_mobile"]').val(),
			tel:$('[name="mod_user_input_tel"]').val(),
			addr:$('[name="mod_user_input_addr"]').val(),
			email:$('[name="mod_user_input_email"]').val(),
			note:$('[name="mod_user_input_note"]').val()
        },access_token:"<?php echo $access_token?>"},function(result){
            var result = JSON.parse(result);
			result = result["rtval"];
			if(result=="done"){
				//刷新数据
				oTable.ajax.reload();
				$('#dlg_<?php echo $G_MODEL_NAME; ?>_form').modal('hide');
			}else{
				alert(result);
			}
        })
		return false;
	},
	 rules: {
		 mod_user_input_name: {
			required: true,
			minlength: 1
		 },
		 mod_user_input_code: {
			required: true,
			minlength: 1,
			remote:{
				url: "<?php echo $G_MODEL_URL;?>",     //后台处理程序  
				type: "post",               //数据发送方式  
				dataType: "json",		  //接受数据格式 
				async: true, 
				beforeSend: function (request) {
					request.setRequestHeader("access_token","<?php echo $access_token?>");
				},
				data: {                      //要传递的数据
					id:       function() {return $('[name="mod_user_input_id"]').val()},
					data:   function() {return $('[name="mod_user_input_code"]').val();},
					action: function() {return 'check_code';},
				}
			}
		 },
		 mod_user_input_user: {
			required: true,
			minlength: 1,
			remote:{
				url: "<?php echo $G_MODEL_URL;?>",     //后台处理程序  
				type: "post",               //数据发送方式  
				dataType: "json",		  //接受数据格式 
				async: true, 
				beforeSend: function (request) {
					request.setRequestHeader("access_token","<?php echo $access_token?>");
				},
				data: {                      //要传递的数据
					id:       function() {return $('[name="mod_user_input_id"]').val()},
					data:   function() {return $('[name="mod_user_input_user"]').val();},
					action: function() {return 'check_user';},
				}
			}
		 },
		 mod_user_input_department: {
			required: true,
			digits: true,
		 },
		 mod_user_input_groups: {
			required: true,
			digits: true 
		 }
	 }
 });

/*初始化list*/
var oTable = $('#<?php echo $G_MODEL_NAME; ?>_list').DataTable({
	"ajax": {
        url:"<?php echo $G_MODEL_URL;?>",
        beforeSend: function (request) {
            request.setRequestHeader("access_token","<?php echo $access_token?>");
        },
        "dataSrc": function ( json ) {
			check_ajax_request(json);
            return json["rtval"]["data"];
        }
    },
	"deferRender": true,
	"iDisplayLength": 25,
	"fnInitComplete": function() {
		// return;
		//数据读取完成事件
		//读取edit框里面的groups和department信息
		var obj;
		ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"get_groups"},access_token:"<?php echo $access_token?>"},function(result){
			try{
				var result = JSON.parse(result);
				obj = result["rtval"];
			}catch(e){
				alert(e);
			}
			$('[name="mod_user_input_groups"]').empty();
			$('[name="mod_user_input_groups"]').append("<option value=\"\"></option>");
			for(v in obj["data"]){
				var id = obj["data"][v]["id"];
				var name = obj["data"][v]["name"];
				$('[name="mod_user_input_groups"]').append('<option value="' + id + '">' + name + '</option>');
			}
			$('[name="mod_user_input_groups"]').trigger("chosen:updated");
		})

		ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"get_department"},access_token:"<?php echo $access_token?>"},function(result){
			try{
				var result = JSON.parse(result);
				obj = result["rtval"];
			}catch(e){
				alert(e);
			}
			$('[name="mod_user_input_department"]').empty();
			$('[name="mod_user_input_department"]').append("<option value=\"\"></option>");
			for(v in obj["data"]){
				var id = obj["data"][v]["id"];
				var name = obj["data"][v]["name"];
				$('[name="mod_user_input_department"]').append('<option value="' + id + '">' + name + '</option>');
			}
			$('[name="mod_user_input_department"]').trigger("chosen:updated");
		})
		
	},
	"oLanguage": {
		"sLengthMenu": "每页显示 _MENU_ 条记录",
		"sZeroRecords": "抱歉， 没有找到",
		"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
		"sInfoEmpty": "没有数据",
		"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
		"sZeroRecords": "没有检索到数据",
		"sSearch": "搜索:",
		"oPaginate": {
			"sFirst": "首页",
			"sPrevious": "前一页",
			"sNext": "后一页",
			"sLast": "尾页"
		}
	},

	"fnRowCallback": function(nRow) {
		
		$(nRow).on('mousedown',
		function(e) {
			if (e.button == 2) {
				if ($(this).hasClass('selected')) {
					//$(this).removeClass('selected');
				} else {
					oTable.$('tr.selected').removeClass('selected');
					$(this).addClass('selected');
				}
				
				doDynamicMenu(0, {
					x: e.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft + 5,
					y: e.clientY + document.documentElement.scrollTop - document.documentElement.clientTop
				});
				return false;
			} else {
				
				if ($(this).hasClass('selected')) {
					//$(this).removeClass('selected');
				} else {
					oTable.$('tr.selected').removeClass('selected');
					$(this).addClass('selected');
				}
			}
			return true;
		});
	},
	dom: '<"html5buttons"B>lTfgitp',
	buttons: [{
		extend: 'copy'
	},
	{
		extend: 'csv'
	},
	{
		extend: 'excel',
		title: 'ExcelFile'
	},
	{
		extend: 'pdf',
		title: 'PDFFile'
	},

	{
		extend: 'print',
		customize: function(win) {
			$(win.document.body).addClass('white-bg');
			$(win.document.body).css('font-size', '10px');

			$(win.document.body).find('table').addClass('compact').css('font-size', 'inherit');
		}
	}]
});


//创建右键菜单
function doDynamicMenu(idx, pos) {
	var $mymenu = $("<div class='mod_menu_<?php echo $G_MODEL_NAME; ?>'/>");
	$("body").append($mymenu);
	$.contextMenu({
		selector: '.mod_menu_<?php echo $G_MODEL_NAME; ?>',
		callback: function(key, options) {
			mod_fun_action(key);
		},
		items: {
			"add": {
				name: "添加",
				className: 'mod_menu_btn_<?php echo $G_MODEL_NAME; ?>_cps_user_001'
			},
			"edit": {
				name: "修改",
				className: 'mod_menu_btn_<?php echo $G_MODEL_NAME; ?>_cps_user_002'
			},
			"delete": {
				name: "删除",
				className: 'mod_menu_btn_<?php echo $G_MODEL_NAME; ?>_cps_user_003'
			},
			"sep1": "---------",
			"password": {
				name: "设置密码",
				className: 'mod_menu_btn_<?php echo $G_MODEL_NAME; ?>_cps_user_005'
			},
			"sep2": "---------",
			"refresh": {
				name: "刷新",
				className: 'mod_menu_btn_<?php echo $G_MODEL_NAME; ?>_cps_user_004'
			}
		}

	});
	$(".mod_menu_<?php echo $G_MODEL_NAME; ?>").contextMenu(pos);
}
 

function mod_fun_action(key){
	oForm.resetForm();
	
	$('#mod_user_input_code-error').hide();
	$('[name="mod_user_input_code"]').removeClass("error");
	$('[name="mod_user_input_code"]').removeAttr("aria-invalid");
	$('[name="mod_user_input_code"]').removeAttr("aria-required");

	$('#mod_user_input_name-error').hide();
	$('[name="mod_user_input_name"]').removeClass("error");
	$('[name="mod_user_input_name"]').removeAttr("aria-invalid");
	$('[name="mod_user_input_name"]').removeAttr("aria-required");
	
	$('#mod_user_input_user-error').hide();
	$('[name="mod_user_input_user"]').removeClass("error");
	$('[name="mod_user_input_user"]').removeAttr("aria-invalid");
	$('[name="mod_user_input_user"]').removeAttr("aria-required");
	
	if(key=="add"){
		$('[name="mod_user_input_id"]').val("");
		$('[name="mod_user_input_code"]').val("");
		$('[name="mod_user_input_name"]').val("");
		$('[name="mod_user_input_user"]').val("");
		
		$("[name='mod_user_input_department']").get(0).selectedIndex = 0;
		$("[name='mod_user_input_groups']").get(0).selectedIndex = 0;
		$('[name="mod_user_input_department"]').trigger("chosen:updated");
		$('[name="mod_user_input_groups"]').trigger("chosen:updated");
		
		$('[name="mod_user_input_stat"]').removeAttr("checked");

		$('[name="mod_user_input_is_department_head"]').removeAttr("checked");
		$('[name="mod_user_input_is_department_headquarters_head"]').removeAttr("checked");

		$('[name="mod_user_input_mobile"]').val("");
		$('[name="mod_user_input_tel"]').val("");
		$('[name="mod_user_input_addr"]').val("");
		$('[name="mod_user_input_email"]').val("");
		$('[name="mod_user_input_note"]').val("");
		$('#dlg_<?php echo $G_MODEL_NAME; ?>_form').modal('show');
		return;
	}
	
	if(key=="edit"){
		var o = oTable.row('.selected');
		//判断没有选中行
		if(typeof(o.data()) == "undefined"){
			return;
		}
		$('[name="mod_user_input_id"]').val(o.data()[0]);
		$('[name="mod_user_input_code"]').val(o.data()[1]);
		$('[name="mod_user_input_name"]').val(o.data()[2]);
		$('[name="mod_user_input_user"]').val(o.data()[3]);
		var i = 0;
		$('[name="mod_user_input_department"]').find("option").each(function(){
			if($(this).text() == o.data()[4]){
				$("[name='mod_user_input_department']").get(0).selectedIndex=i;
			}
			i++;
		});
		$('[name="mod_user_input_department"]').trigger("chosen:updated");
		
		if(o.data()[5]=="是"){
			$('[name="mod_user_input_is_department_head"]').prop("checked","checked");
		}else{
			$('[name="mod_user_input_is_department_head"]').removeAttr("checked");
		}
		if(o.data()[6]=="是"){
			$('[name="mod_user_input_is_department_headquarters_head"]').prop("checked","checked");
		}else{
			$('[name="mod_user_input_is_department_headquarters_head"]').removeAttr("checked");
		}
		var i=0;
		$('[name="mod_user_input_groups"]').find("option").each(function(){
			if($(this).text() == o.data()[7]){
				$("[name='mod_user_input_groups']").get(0).selectedIndex=i;
			}
			i++;
		});
		$('[name="mod_user_input_groups"]').trigger("chosen:updated");

		if(o.data()[8]=="开启"){
			$('[name="mod_user_input_stat"]').prop("checked","checked");
		}else{
			$('[name="mod_user_input_stat"]').removeAttr("checked");
		}

		$('[name="mod_user_input_mobile"]').val(o.data()[9]);
		$('[name="mod_user_input_tel"]').val(o.data()[10]);
		$('[name="mod_user_input_addr"]').val(o.data()[11]);
		$('[name="mod_user_input_email"]').val(o.data()[12]);
		$('#dlg_<?php echo $G_MODEL_NAME; ?>_form').modal('show');
		
		return;
	}
	
	if(key=="delete"){
		var o = oTable.row('.selected');
		//判断没有选中行
		if(typeof(o.data()) == "undefined"){
			return;
		}
		swal({ 
          title: '确定删除该记录', 
          text: '如果删除该记录,数据将无法恢复!', 
          type: 'warning',
          showCancelButton: true, 
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: '删除！',
          cancelButtonText: '取消！', 
        }).then(function(result){
            if (result.value) {
                //删除当前选择行
				var id = o.data()[0];
				ajax_request({url:"<?php echo $G_MODEL_URL;?>",type:"POST",dataType:"TEXT",data:{action:"delete",id:id},access_token:"<?php echo $access_token?>"},function(result){
                    var result = JSON.parse(result);
                    result = result["rtval"];
                    if(result=="done"){
                        //刷新数据
                        oTable.ajax.reload();
                        swal(
                            '已经删除!',
                            '该记录已被成功删除',
                            'success'
                        );
                    }else{
                        oTable.ajax.reload();
                        swal(
                            '无法删除!',
                            result,
                            'error'
                        );
                        
                    }
                })
            } 
        })
				
		return;
	}
	
	
	if(key=="password"){
		var o = oTable.row('.selected');
		//判断没有选中行
		if(typeof(o.data()) == "undefined"){
			return;
		}
		var id = o.data()[0];
		$('[name="mod_user_input_id_password_setting"]').val(id);
		$('[name="mod_user_input_password"]').val("");
		$('[name="mod_user_input_repassword"]').val("");
		
		$('#dlg_<?php echo $G_MODEL_NAME; ?>_password_setting').modal('show');
		
	}
	
	
	if(key=="refresh"){
		//刷新数据
		oTable.ajax.reload();
		return;
	}
	
	return;
}
